package com.app.toknow.Common;

import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by kangw on 2015/10/2.
 */
public class ConnectWSHelper {
    private static final String TAG = "ConnectWSHelper";
    private static String NAME_SPACE = "http://www.toknow.com/";
    private static String SERVER_IP = "192.168.0.2";
    private static String SERVER_PORT = "8088";

    public static String GetResponse(String MethodName, Map<String, String> Params) {
        String result = null;
        String WSDL_URL = "http://"+ SERVER_IP +":"+ SERVER_PORT +"/"+ WSAPIMethodName.USERINFO_API +".asmx?wsdl";
        // 指定webService命名空间和调用的方法，可以从WSDL的文档中找到
        SoapObject request = new SoapObject(NAME_SPACE, MethodName);
        // 设置调用方法的参数值,第一个参数是键值对的键，第二个是键值对的值
//        request.addProperty("arg0", "caiguan");
        // 2、设置调用方法的参数值，如果没有参数，可以省略，
        if (Params != null) {
            Iterator iter = Params.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                request.addProperty((String) entry.getKey(),
                        (String) entry.getValue());
            }
        }
        // 生成调用WebService方法的soap请求信息，该信息由SoapSerializationEnvelop对象描述

        /**
         * 1.创建SoapSerializationEnvelope对象时，需要用它的构造方法设置SOAP协议的版本号，
         * 该版本号需要根据WebService端的版本号设置。
         * 2.创建好SoapSerializationEnvelope后，要设置它的bodyOut属性
         * ，属性的值，就是前面创造的SoapObject对象
         */
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.bodyOut = request;
        envelope.setOutputSoapObject(request);
        envelope.dotNet = true;
        // 创建HttpTransportsSE对象，通过这个对象的构造方法，可以指定WebService的WSDL文档中的URL
        //localhost或者127.0.0.1 改为 ----- > 10.0.2.2
        HttpTransportSE httpTran = new HttpTransportSE(WSDL_URL,5000);
        httpTran.debug = true;
        // 使用Call方法调用WebService方法。
        try {
             httpTran.call(NAME_SPACE+MethodName,envelope);
//            httpTran.call(null, envelope);
        } catch (IOException e) {
            Log.e("----发生错误IOException:---", e.getMessage());
            String err = e.getMessage().indexOf("Network is unreachable")>0?"网络不可用":e.getMessage();
            err = err.indexOf("after 5000")>0?"连接超时！":err;
            result = "{\"STATE\":0,\"MESSAGE\":\""+ err +"\",\"CLASS\":\"Simple\"}";
            return result.toString();
        } catch (XmlPullParserException e) {
            Log.e("----发生错误XmlPull---", e.getMessage());
            result = "{\"STATE\":0,\"MESSAGE\":\""+ e.getMessage() +"\",\"CLASS\":\"Simple\"}";
            return result.toString();
        }
        // 使用getResponse方法获得WebService方法的返回结果
        // 使用bodyin方法获得返回结果
        //	SoapObject result = (SoapObject) envelope.bodyIn;

        try {
            result = ((SoapPrimitive) envelope.getResponse()).toString();
        } catch (SoapFault e) {
            Log.e("----发生错误---", e.getMessage());
            result = "{\"STATE\":0,\"MESSAGE\":\""+ e.getMessage() +"\",\"CLASS\":\"Simple\"}";
        }catch (Exception e) {
            Log.e("----发生错误Exception:---", e.getMessage());
            result = "{\"STATE\":0,\"MESSAGE\":\""+ e.getMessage() +"\",\"CLASS\":\"Simple\"}";
        }
        return result.toString();
    }
    /**
     *
     * @param result JSON字符串
     * @param name   JSON数组名称
     * @param fields JSON字符串所包含的字段
     * @return       返回List<map<string,object>>类型的列表，Map<string,object>对应于 id:1的结构
     */
    public static List<Map<String, Object>> convertJSON2List(String result,
                                                                String name, String[] fields) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        try {
            JSONArray array = new JSONObject(result).getJSONArray(name);

            for (int i = 0; i < array.length(); i++) {
                JSONObject object = (JSONObject) array.opt(i);
                Map<String, Object> map = new HashMap<String, Object>();
                for (String str : fields) {
                    map.put(str, object.get(str));
                }
                list.add(map);
            }
        } catch (JSONException e) {
            Log.e(TAG, e.getMessage());
        }
        return list;
    }

}
